import { useCallback, useEffect } from 'react';
import { useChat as useChatContext } from './useChatContext';
import { useWebSocket } from './useWebSocketHook';
import { generateUUID, generateUserColor } from '../utils/common';
import type { Message, User } from '../types';

export const useChatHook = () => {
  const { state, dispatch } = useChatContext();
  const { socket, connectionStatus, realConnectionStatus, sendMessage, connect, disconnect } = useWebSocket();

  const handleMessage = useCallback((event: MessageEvent) => {
    try {
      // 检查事件数据是否存在
      if (!event || !event.data) {
        console.warn('Received empty WebSocket event');
        return;
      }
      
      const data = JSON.parse(event.data) as unknown;
      
      // 检查解析后的数据是否有效
      if (!data || typeof data !== 'object') {
        console.warn('Invalid message received:', data);
        return;
      }
      
      if (typeof data === 'object' && data !== null) {
        const message = data as { type?: string; [key: string]: unknown };
        
        
        // 处理消息格式（后端发送的直接消息格式）
        if (message.type === 'message' && 'content' in message && 'username' in message) {
          // 这是后端直接发送的消息格式
          const userId = (message.userId as string) || (message.username as string) || 'unknown';
          const validatedMessage: Message = {
            id: generateUUID(),
            type: 'text',
            username: (message.username as string) || 'Unknown',
            userId: userId,
            dateTime: new Date().toISOString(),
            timestamp: message.timestamp ? new Date(message.timestamp as number) : new Date(),
            randomColor: generateUserColor(userId), // 使用确定性颜色算法
            message: (message.content as string) || '',
          };
          
          dispatch({ type: 'ADD_MESSAGE', payload: validatedMessage });
        }
        // 处理包装的消息格式 {type: 'message', message: ...}（如果需要支持）
        else if (message.type === 'message' && 'message' in message) {
          const messageData = message as { message: Message };
          const receivedMessage = messageData.message;
          
          // 验证并补全消息字段
          if (receivedMessage && typeof receivedMessage === 'object' && receivedMessage !== null) {
            if (receivedMessage.type === 'file') {
              const userId = receivedMessage.userId || receivedMessage.username || 'unknown';
              const fileMsg: Message = {
                id: receivedMessage.id || generateUUID(),
                type: 'file' as const,
                username: receivedMessage.username || 'Unknown',
                userId: userId,
                dateTime: receivedMessage.dateTime || new Date().toISOString(),
                timestamp: receivedMessage.timestamp ? new Date(receivedMessage.timestamp) : new Date(),
                randomColor: generateUserColor(userId), // 使用确定性颜色算法
                message: receivedMessage.message || '',
                fileName: (receivedMessage as { fileName?: string }).fileName || '',
                fileSize: (receivedMessage as { fileSize?: number }).fileSize || 0,
                filePath: (receivedMessage as { filePath?: string }).filePath,
                fileType: (receivedMessage as { fileType?: string }).fileType,
                fileHash: (receivedMessage as { fileHash?: string }).fileHash || ''
              };
              dispatch({ type: 'ADD_MESSAGE', payload: fileMsg });
            } else {
              const userId = receivedMessage.userId || receivedMessage.username || 'unknown';
              const textMsg: Message = {
                id: receivedMessage.id || generateUUID(),
                type: 'text' as const,
                username: receivedMessage.username || 'Unknown',
                userId: userId,
                dateTime: receivedMessage.dateTime || new Date().toISOString(),
                timestamp: receivedMessage.timestamp ? new Date(receivedMessage.timestamp) : new Date(),
                randomColor: generateUserColor(userId), // 使用确定性颜色算法
                message: receivedMessage.message || ''
              };
              dispatch({ type: 'ADD_MESSAGE', payload: textMsg });
            }
          } else {
            console.warn('Invalid message received:', receivedMessage);
          }
        }
        else {
           // 处理其他类型的消息
           switch (message.type) {
             case 'user_joined':
               // 用户加入事件，暂时不处理
               break;
             case 'user_left':
               // 用户离开事件，暂时不处理
               break;
            case 'server-info': {
              // 将HTTP基础地址暴露在window上，供上传HTTP使用
              const info = message as { webPort?: number };
              if (typeof info.webPort === 'number') {
                (window as { __API_BASE__?: string }).__API_BASE__ = `http://` + window.location.hostname + `:` + info.webPort;
              }
              break;
            }
             case 'file-start': {
               // 文件开始上传 - 只为其他用户显示上传开始消息
               const fileStartData = message as {
                 fileHash: string;
                 fileName: string;
                 fileSize: number;
                 username: string;
                 userId: string;
                 randomColor: string;
                 dateTime: string;
               };
               
               // 移除用户ID检查，让所有用户都能看到文件上传开始
                 const userId = fileStartData.userId || 'unknown';
                 const fileMessage: Message = {
                   id: generateUUID(),
                   type: 'file',
                   username: fileStartData.username || 'Unknown',
                   userId: userId,
                   dateTime: fileStartData.dateTime || new Date().toISOString(),
                   timestamp: new Date(),
                   randomColor: generateUserColor(userId), // 使用确定性颜色算法
                   message: `正在上传文件: ${fileStartData.fileName}`,
                   fileName: fileStartData.fileName,
                   fileSize: fileStartData.fileSize,
                   fileHash: fileStartData.fileHash,
                   uploadProgress: 0
                 };
                 
                 dispatch({ type: 'ADD_MESSAGE', payload: fileMessage });
               break;
             }
             case 'file-progress': {
               // 文件上传进度更新
               const progressData = message as { fileHash: string; progress: number };
               dispatch({ 
                 type: 'UPDATE_FILE_PROGRESS', 
                 payload: { fileHash: progressData.fileHash, progress: progressData.progress }
               });
               
               // 同时更新对应的文件消息的进度
               dispatch({
                 type: 'UPDATE_MESSAGE_PROGRESS',
                 payload: { fileHash: progressData.fileHash, progress: progressData.progress }
               });
               break;
             }
             case 'file-complete': {
               // 文件上传完成
               const completeData = message as {
                 fileHash: string;
                 filePath: string;
                 fileName: string;
                 fileSize: number;
                 username: string;
                 userId: string;
                 randomColor: string;
                 dateTime: string;
                 progress?: number; // 添加progress字段
               };
               
              const finalProgress = completeData.progress || 100;
              dispatch({
                type: 'UPDATE_MESSAGE_PROGRESS',
                payload: { fileHash: completeData.fileHash, progress: finalProgress }
              });
              dispatch({
                type: 'SET_FILE_MESSAGE_COMPLETE',
                payload: { fileHash: completeData.fileHash, filePath: completeData.filePath, fileName: completeData.fileName }
              });
               break;
             }
             case 'file-error': {
               // 文件上传失败
               const errorData = message as {
                 fileHash: string;
                 fileName: string;
                 error: string;
               };
               
               console.error(`文件上传失败: ${errorData.fileName}`, errorData.error);
               
               dispatch({
                 type: 'SET_FILE_MESSAGE_ERROR',
                 payload: { fileHash: errorData.fileHash, errorMessage: `文件上传失败: ${errorData.fileName} - ${errorData.error}` }
               });
               break;
             }
             case 'chunk-received': {
               // 文件块接收确认 - 触发自定义事件供useFileUpload监听
               const chunkData = message as { fileHash: string; chunkIndex: number; type?: string; error?: string };
               console.log(`Chunk ${chunkData.chunkIndex} received for file ${chunkData.fileHash}`);
               
               // 触发自定义事件
               window.dispatchEvent(new CustomEvent('chunk-received', {
                 detail: chunkData
               }));
               break;
             }
             case 'file-exists': {
               // 文件存在性检查结果（存在） -> 通过自定义事件通知上传逻辑
               const existsData = message as { fileHash: string; filePath: string };
               window.dispatchEvent(new CustomEvent('file-check-result', {
                 detail: { fileHash: existsData.fileHash, type: 'file-exists', filePath: existsData.filePath }
               }));
               break;
             }
             case 'file-not-exists': {
               // 文件存在性检查结果（不存在） -> 通知上传逻辑
               const notExistsData = message as { fileHash: string };
               window.dispatchEvent(new CustomEvent('file-check-result', {
                 detail: { fileHash: notExistsData.fileHash, type: 'file-not-exists' }
               }));
               break;
             }
             default:
               console.log('Unknown message type:', message.type);
           }
        }
      }
    } catch (error) {
      console.error('Failed to parse WebSocket message:', error);
    }
  }, [dispatch]);

  // 处理WebSocket消息
  useEffect(() => {
    if (!socket) return;

    socket.addEventListener('message', handleMessage);

    return () => {
      socket.removeEventListener('message', handleMessage);
    };
  }, [socket, handleMessage]);

  // 更新连接状态
  useEffect(() => {
    dispatch({ type: 'UPDATE_CONNECTION_STATUS', payload: connectionStatus });
  }, [connectionStatus, dispatch]);

  // 发送文本消息
  const sendTextMessage = useCallback((content: string) => {
    if (!content.trim() || !state.user) return;

    const message = {
        type: 'message',
        content: content.trim(),
        username: state.user.username,
        userId: state.user.userId,
        randomColor: state.user.randomColor, // 包含用户颜色
        timestamp: Date.now(),
      };

    sendMessage(message);
    // 不再立即添加到本地，等待服务器广播回来
  }, [state.user, sendMessage]);

  // 设置用户
  const setUser = useCallback((user: User) => {
    dispatch({ type: 'SET_USER', payload: user });
    
    // 发送用户加入消息
    if (socket?.readyState === WebSocket.OPEN) {
      sendMessage({
        type: 'user_join',
        user: user.username,
        timestamp: Date.now(),
      });
    }
  }, [dispatch, socket, sendMessage]);

  // 清空消息
  const clearMessages = useCallback(() => {
    dispatch({ type: 'CLEAR_MESSAGES' });
  }, [dispatch]);

  // 删除消息
  const deleteMessage = useCallback((messageId: string) => {
    dispatch({ type: 'DELETE_MESSAGE', payload: messageId });
  }, [dispatch]);

  return {
    user: state.user,
    messages: state.messages,
    connectionStatus: realConnectionStatus, // 使用真实的连接状态
    sendTextMessage,
    setUser,
    clearMessages,
    deleteMessage,
    connect,
    disconnect,
  };
}